package com.example.back.service.impl;

import com.example.back.dto.req.DrugTabooEditReq;
import com.example.back.dto.req.DrugTabooListReq;
import com.example.back.dto.resp.DrugTabooListResp;
import com.example.back.jpa.SysKeysRepository;
import com.example.back.mapper.SysKeysMapper;
import com.example.back.service.DrugTabooService;
import com.example.common.entity.Keys;
import com.example.common.support.ApiException;
import com.example.common.utils.CheckUtils;
import com.example.common.utils.IdUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import org.javers.spring.annotation.JaversAuditable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 用药禁忌
 */
@Service
public class DrugTabooServiceImpl implements DrugTabooService {


    @Resource
    private SysKeysMapper sysKeysMapper;

    @Resource
    private SysKeysRepository sysKeysRepository;

    /**
     * 获取用药禁忌列表
     */
    @Override
    public PageInfo<DrugTabooListResp> list(DrugTabooListReq req) {
        CheckUtils.checkNull(req, new ApiException(1, "对象不能为空"));

        //分页页码，默认1页
        int pageNumber = null == req.getPage() ? 1 : req.getPage();
        //分页条数，默认10条
        int pageSize = null == req.getLimit() ? 10 : req.getLimit();
        //药品用法名称
        String name = req.getName();
        int types = 1;
        return PageHelper
                .startPage(pageNumber, pageSize)
                .doSelectPageInfo(() -> sysKeysMapper.findSysKeysName(name,types));
    }

    /**
     * 修改和添加用药禁忌
     */
    @Override
    @JaversAuditable
    public Object commitSave(DrugTabooEditReq req) {

        if(req.getId() ==0){

            Keys keys = new Keys();
            keys.setId(IdUtils.generateId());
            keys.setName(req.getName());
            keys.setCode("");
            keys.setSort(0);
            keys.setTypes(1);
            return sysKeysRepository.save(keys);
        }else{
            Keys objs = sysKeysRepository.findById(req.getId()).orElse(null);
            if(objs == null){
                throw new ApiException(1, "错误的请求参数");
            }
            objs.setName(req.getName());
            return sysKeysRepository.save(objs);
        }
    }

    /**
     * 删除用药禁忌
     */
    @Override
    @JaversAuditable
    public Object commitDel(DrugTabooEditReq req) {

        Keys objs = sysKeysRepository.findById(req.getId()).orElse(null);
        if(objs == null){
            throw new ApiException(1, "错误的请求参数");
        }
        sysKeysRepository.deleteById(req.getId());
        return null;
    }
}
